<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增考勤</title>
<jsp:include page="${home}/assets/common_inc_new.jsp"  flush="true"></jsp:include>
<script type="text/javascript" src="${home}/system/common/scripts/zDialog.js"></script>
<script type="text/javascript" src="${home}/system/common/scripts/utils.js"></script>
<link rel="stylesheet" type="text/css" href="../css/index.css">
<link rel="stylesheet" type="text/css" href="../css/add.css">


<style>
	/* *{
		font-weight: 400;
	}*/
	.btn{
		width: 125px;
		height: 40px;
		margin: 0px 40px 0 0;
		border: 1px solid #288ff4;
		color: #288ff4;
		font-size: 16px;
		background-color: #fff;
		border-radius: 5px;
	}
	.Validform_checktip{
		color: red;
		margin-right: 10px;
		font-size: 18px;
	}
	.th_check {
		margin-left: 10px;
		vertical-align: sub;
	}
</style>
<%
  String application_id =request.getParameter("application_id");
  String dept_id =request.getParameter("dept_id");
 %>

<script type="text/javascript">
function getYMD(){
  var date = new Date();
  var seperator1 = "-";
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
       month = "0" + month;
   }
  if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
   }
  return date.getFullYear() + seperator1 + month + seperator1 + strDate;
}



function batchAdd() {
  $("#batch_add_pane").fadeIn();
}

function cancelModel(id) {
  $("#" + id).fadeOut();
}

function obj2Str(obj) {
  return JSON.stringify(obj).replace(/"/g, "'");
}

function buildClickTd(item, row, schedule) {
  var itemStr = obj2Str(item);
  return "<td align=\"center\" class=\"click-td\" onclick=\"choose(" + itemStr + ", " + row + ", '" + schedule + "');\">"
  + "<img src=\"../assets/v.png\" class=\"v\" id=\"v_" + row + "_" + schedule + "\">"
  + "</td>";
}

function buildInputTd(row, name, value) {
  return "<td align=\"center\">"
  + "<input onchange=\"fill(" + row + ", '" + name + "');\" id=\"i_" + row + "_" + name + "\" class=\"td-input\" type=\"text\" value=\"" + value + "\">"
  + "</td>";
}

function buildTd(value) {
  return "<td align=\"center\">" + value + "</td>";
}

function buildTdNum(row) {
  return "<td align=\"center\">"
	 + (row + 1)
	 + "<input class=\"th_check\" type=\"checkbox\" id=\"all_" + row + "\">"
	 + "</td>";
}

function buildTableDataUI(data){
	$("#resultgrid tr:gt(1)").remove();
  for (var i = 0; i < data.length; i++) {
    var item = data[i];
    var html = "<tr>"
    + buildTdNum(i)
    + buildTd(item.name)
    + buildClickTd(item, i, 'am')
    + buildClickTd(item, i, 'pm')
    + buildClickTd(item, i, 'night')
    + buildClickTd(item, i, 'day')
    + buildInputTd(i, 'workValue', '')
    + buildInputTd(i, 'midnight', '')
    + "</tr>";
    $("#resultgrid").append(html);
		initCheckChange("all_" + i, 0, '', i);
  }
}

var scheduleTypeMap ={
  am: 1,
  pm: 2,
  night: 4,
  day: 8
};
function choose(user, row, schedule) {
  var v = "#v_" + row + "_" + schedule;
  const attend = attendData[row];
  if (attend[schedule]) {
    delete attend[schedule];
    $(v).hide();
  } else {
    attend[schedule] = scheduleTypeMap[schedule];
    $(v).show();
  }
}

function fill(row, name) {
  var v = "#i_" + row + "_" + name;
  const attend = attendData[row];
  attend[name] = $(v).val();
}

var diag;
var approvalBtnId
function queryApproval(id) {
	// 判断，审批人员必须按照顺序一个个添加，不可以乱序添加
	var auditLevel = parseInt(id.substring(13));
	if(auditLevel != 1){
		var lastLevel = auditLevel - 1;
		if(!$('#approval-btn-'+lastLevel).attr('approval_id')){
			// alert("上一级审批人员不能为空");
			return;
		}
	}

    approvalBtnId = id;
    diag = new Dialog();
    diag.Width = 950;
    diag.Height = 620;
    diag.Title = "";
    diag.URL = "approval.jsp";
	//diag.URL = "choosepage.jsp";
    diag.ShowMessageRow = false;
    diag.show();
}

function addApproval(approval) {
  $("#" + approvalBtnId).val(approval.name);
  $("#" + approvalBtnId).attr('approval_id', approval.id);
}

function delApproval(id){
	$("#" + approvalBtnId).val("");
   $("#" + approvalBtnId).attr('approval_id', '');
}

function back() {
  window.location.href = "index.jsp";
}

function insert(saveAndCommit) {
  var head={
    "service_name":"cn.dy.workatten.service.WorkAttenService",
    "operation_name":"createNewWorkAtten"
  };
  var params = buildParams();
  var param={
    "dept_id": $("#dept_id").val(),
    "dateStr": $("#dateStr").val(),
    "staff_Ids": params.staff_Ids,
    "schedule_Ids": params.schedule_Ids,
    "man_hour_midnights": params.man_hour_midnights,
    "work_values": params.work_values,
    "audit1": $('#approval-btn-1').attr('approval_id'),
    "audit2": $('#approval-btn-2').attr('approval_id'),
    "audit3": $('#approval-btn-3').attr('approval_id'),
    "audit4": $('#approval-btn-4').attr('approval_id'),
    "audit5": $('#approval-btn-5').attr('approval_id'),
	"saveAndCommit": saveAndCommit
  };
  var options = {
    "handleError": false,
    "showProgressBar":false,
    "timeout":60000*10
  };
  var cb = function(data, result) {
	if(data.response_code==0){
		alert(data.response_desc);
		back();
	}else{
		alert(data.response_desc);
	}

    // $.dialog.tips(result.response_code == '0' ? "新增考勤成功" : "新增考勤失败");
    // back();
  }
  $.ServiceAgent.JSONInvoke(head, param, cb, options);
}

function update() {
  var head={
    "service_name":"cn.dy.workatten.service.WorkAttenService",
    "operation_name":"modifyWorkAtten"
  };
  var params = buildParams();
  var param={
    "attend_application_id": application_id,
    "dept_id": dept_id,
    "dateStr": $("#dateStr").val(),
    "staff_Ids": params.staff_Ids,
    "schedule_Ids": params.schedule_Ids,
    "man_hour_midnights": params.man_hour_midnights,
    "work_values": params.work_values,
    "audit1": $('#approval-btn-1').attr('approval_id'),
    "audit2": $('#approval-btn-2').attr('approval_id'),
    "audit3": $('#approval-btn-3').attr('approval_id'),
    "audit4": $('#approval-btn-4').attr('approval_id'),
    "audit5": $('#approval-btn-5').attr('approval_id')
  };
  var options = {
    "handleError": false,
    "showProgressBar":false,
    "timeout":60000*10
  };
  var cb = function(data, result) {
    $.dialog.tips(result.response_code == '0' ? "修改考勤成功" : "修改考勤失败");
    setTimeout(back, 1000);
  }
  $.ServiceAgent.JSONInvoke(head, param, cb, options);
}

function save() {
  if (!$('#approval-btn-1').attr('value')) {
    alert("一级审批人员不能为空");
    return;
  }
  if (!application_id || application_id == "null") {
    insert(0);
  } else {
    update();
  }
}

function submit() {
  if (!application_id || application_id == "null") { // 直接点击提交审核，没有进行过保存
	insert(1);
    return;
  }
  var head={
    "service_name":"cn.dy.workatten.service.WorkAttenService",
    "operation_name":"commitAudit"
  };
  var param={
    "attend_application_id": application_id
  };
  var options = {
    "handleError": false,
    "showProgressBar":false,
    "timeout":60000*10
  };
  var cb = function(data, result) {
    $.dialog.tips(result.response_code == '0' ? "提交审批成功" : "提交审批失败");
    setTimeout(back, 1000);
  }
  $.ServiceAgent.JSONInvoke(head, param, cb, options);
}

function ui_listReqInfos() {
	queryUsers();
}

function getAddData() {
  var addData = [];
  console.log(attendData);
  for (var i = 0; i < attendData.length; i++) {
    var attend = attendData[i];
    if (attend.am || attend.pm || attend.night
       || attend.day || attend.workValue || attend.midnight) {
      addData.push(attend);
     }
  }
  return addData;
}

function buildScheduleId(item) {
  var scheduleId = '';
  if (item.am) {
    scheduleId += item.am + ",";
  }
  if (item.pm) {
    scheduleId += item.pm+ ",";
  }
  if (item.night) {
    scheduleId += item.night+ ",";
  }
  if (item.day) {
    scheduleId += item.day+ ",";
  }
  if (scheduleId) {
    scheduleId = scheduleId.substring(0, scheduleId.length - 1);
  }
  return scheduleId;
}

function buildParams() {
  var addData = getAddData();
  var staff_Ids = [];
  var schedule_Ids = [];
  var man_hour_midnights = [];
  var work_values = [];
  for (var i = 0; i < addData.length; i++) {

    var item = addData[i];
    staff_Ids.push(item.id);
    schedule_Ids.push(buildScheduleId(item));
	if(item.midnight){
		man_hour_midnights.push(item.midnight);
	} else{
		man_hour_midnights.push(0);
	}
	if(item.workValue) {
		 work_values.push(item.workValue);
	} else{
		 work_values.push(0);
	}
  }
  return {
    staff_Ids: staff_Ids,
    schedule_Ids: schedule_Ids,
    man_hour_midnights: man_hour_midnights,
    work_values: work_values
  }
}

function batchAddConfirm() {
	var rowsArr = Object.keys(rows);
	var scheduleArr = Object.keys(schedules);
	if (!rowsArr.length) {
		alert('请选择行复选框');
		cancelModel('batch_add_pane');
		return;
	}
	if (!scheduleArr.length) {
		alert('请选择列复选框');
		cancelModel('batch_add_pane');
		return;
	}
	for (var i = 0; i < rowsArr.length; i++) {
		const attend = attendData[rowsArr[i]];
		for (var j = 0; j < scheduleArr.length; j++) {
		  if (!attend[scheduleArr[j]]) {
				choose({}, rowsArr[i], scheduleArr[j]);
			}
		}
	}
  cancelModel('batch_add_pane');
}

function buildRecordsMap(data) {
  var map = {};
  for (var i = 0; i < data.attendRecordList.length; i++) {
    var record = data.attendRecordList[i];
    if (!map[record.staff_id]) {
      map[record.staff_id] = [];
    }
    map[record.staff_id].push(record);
  }
  return map;
}

var typeScheduleMap ={
  "1": 'am',
  "2": 'pm',
  "4": 'night',
  "8": 'day'
};
function initData(data) {
  var recordsMap = buildRecordsMap(data);
  for (var i = 0; i < attendData.length; i++) {
    var attend = attendData[i];
    var records = recordsMap[attend.id];
    if (records) {
      for (var j = 0; j < records.length; j++) {
        var record = records[j];
        if (record.scheduleCheckType) {
          var scheduleArr = record.scheduleCheckType.split(',');
          if (scheduleArr && scheduleArr.length) {
            for (var k = 0; k < scheduleArr.length; k++) {
              var type = scheduleArr[k];
              var schedule = typeScheduleMap[type];
              var v = "#v_" + i + "_" + schedule;
              record[schedule] = type;
              $(v).show();

			  // 设置缓存值
			  if(type == '1'){
				attend.am = '1';
			  } else if(type == '2'){
				attend.pm = '2';
			  } else if(type == '4'){
				attend.night = '4';
			  } else if(type == '8'){
				attend.day = '8';
			  }
            }
          }
        }
		var workKey = "#i_" + i + "_workValue";
		$(workKey).val(record.work_value);
		attend.workValue = record.work_value;
		var midKey = "#i_" + i + "_midnight";
		$(midKey).val(record.man_hour_midnight);
		attend.midnight = record.man_hour_midnight;
      }
    }
  }
}

function initAuditingDetail(auditingDetailList) {
  if (!auditingDetailList || !auditingDetailList.length) {
    return;
  }
  for (var i = 0; i < auditingDetailList.length; i++) {
    var item = auditingDetailList[i];
    $("#approval-btn-" + (i + 1)).text(item.auditName);
    $("#approval-btn-" + (i + 1)).attr('approval_id', item.audit_id);
	$("#approval-btn-" + (i + 1)).attr('value', item.auditName);
  }
}

function getWorkAttendDetail() {
  var head={
    "service_name":"cn.dy.workatten.service.WorkAttenService",
    "operation_name":"getWorkAttendDetail"
  };
  var param={
    "attend_application_id": application_id
  };
  var options = {
    "handleError": false,
    "showProgressBar":false,
    "timeout":60000*10
  };
  var cb = function(data, result) {
    if(result.response_code == '0'){
      $.dialog.tips("查询成功...");
      console.log('==================');
      console.log(data);
	  var attendApp = data.content.attendApplication;
	  $("#dateStr").val(attendApp.attendanceDayStr);
	  $("#current_date").text(attendApp.attendanceDayStr);
	  $("#dept_id").val(dept_id);
	  $("#txtdept").val(attendApp.deptName);
	  $("#deptName").text(attendApp.deptName);
      initData(data.content);
      initAuditingDetail(data.content.auditingDetailList);
    }
  }
  $.ServiceAgent.JSONInvoke(head, param, cb, options);
}

var attendData = [];
function queryUsers() {
  var head={
    "service_name":"cn.dy.workatten.service.WorkAttenService",
    "operation_name":"getContactInfoByDept"
  };
  if(right_click_node.id > 0 ){
		dept_id = right_click_node.id;
	}
	console.log($("#dept_id").val() + '-22223334--' + dept_id)

  var param={
    "dept_id": $("#dept_id").val() || dept_id,
    "query": "",
    "pageNum": 0,
    "pageSize": 0
  };
  var options = {
    "handleError": false,
    "showProgressBar":false,
    "timeout":60000*10
  };
  var cb = function(data, result) {
    if(data != null){
      $.dialog.tips("查询成功...");
      console.log('--------data-----------');
      console.log(data);
      attendData = data.content.result;
      buildTableDataUI(attendData);
      if (application_id) {
        getWorkAttendDetail();
      }
    }
  }
  $.ServiceAgent.JSONInvoke(head, param, cb, options);
}

function dateChoose(){
	$("#current_date").text($("#dateStr").val());
}

var rows = {};
var schedules = {};
function initCheckChange(id, type, schedule, row) {
	$("#" + id).change(function() {
		if (!attendData || !attendData.length) {
			return;
		}
		var isCheck = $("#" + id).prop('checked');
		if (type) {
			if (isCheck) {
				schedules[schedule] = schedule;
			} else {
				const rowsArr2 = Object.keys(rows);
				for (var i = 0; i < rowsArr2.length; i++) {
					if (attendData[rowsArr2[i]][schedule]) {
						choose({}, rowsArr2[i], schedule);
					}
				}
				delete schedules[schedule];
			}
		} else {
			if (isCheck) {
				rows[row] = row;
			} else {
				const schedulesArr2 = Object.keys(schedules);
				for (var i = 0; i < schedulesArr2.length; i++) {
					if (attendData[row][schedulesArr2[i]]) {
						choose({}, row, schedulesArr2[i]);
					}
				}
				delete rows[row];
			}
		}
	});
}

var application_id;
var dept_id;
$(function() {
  application_id = "<%=application_id%>";
  dept_id = "<%=dept_id%>";
	application_id = application_id == 'null' ? '' : application_id;
	dept_id = dept_id == 'null' ? '' : dept_id;
  if (application_id && dept_id) { // 修改操作
    queryUsers();
  } else { // 新增
	$("#dateStr").val(getYMD());
	$("#current_date").text(getYMD());
  }

	initCheckChange('all_am', 1, 'am');
	initCheckChange('all_pm', 1, 'pm');
	initCheckChange('all_night', 1, 'night');
	initCheckChange('all_day', 1, 'day');
});
</script>

</head>
<body class="mainbody">
	<!--导航栏-->
    <div class="location">
        <a onclick="back();" class="back"><i></i><span>返回管理页面</span></a>
        <i class="arrow"></i>
        <span id="lbTitle">考勤管理</span>
    </div>

	<div class="toolbar-wrap">
		<div id="floatHead" class="toolbar">
			<div class="r-list" style="float: none">
				<input type="hidden" name="部门id" id="dept_id" class="operation_date" placeholder="部门id" />
				<input type="text" name="txtdept" id="txtdept" for="txtdept" placeholder="请选择部门" style="float: left" sucmsg=" " style="width: 150px;" class="keyword date" readonly="readonly" onclick="ShowAction()" />
				<span class="operation_time">考勤日期:</span>
				<input name="begin_time" type="text" id="dateStr"
					class="keyword date"
					onfocus="WdatePicker({dateFmt:&#39;yyyy-MM-dd&#39;})" onblur="dateChoose();"
					datatype="*1-50" errormsg="请选择正确的日期" sucmsg=" " nullmsg=" "
					placeholder=""  />
				<!--<a id="lbtnSearch" class="reset" onclick="queryGrid();"><span>查询</span></a>
				<a class="reset" onclick="batchAdd();"><span>批量录入</span></a> -->
				<a id="lbtnSearch" class="btn-search" onclick="ui_listReqInfos();"><i></i><span>查询</span></a>
			</div>

			<div class="l-list">
				<ul class="icon-list">
					<li>
						<a id="lbtnAdd" class="add" onclick="batchAdd();"><i></i><span>批量录入</span></a>
					</li>
				</ul>
			</div>
		</div>
    <div class="workatten-top">
      部门: <span id="deptName"></span>
      <span class="current-date">
        考勤日期: <span class="current-date" id="current_date"></span>
      </span>
    </div>
    <table width="100%" border="0" cellpadding="0" cellpadding="0" class="ltable" id="resultgrid">
			<tr>
				<th width="10%" rowspan="2">序号</th>
				<th width="10%" rowspan="2" class="name-date">
          <span class="name">姓名</span>
          <span class="datetxt">日期</span>
        </th>
        <th width="13%" colspan="6">1日</th>
			</tr>
			<tr>
				<th width="13%">
					上午<input class="th_check" type="checkbox" id="all_am">
				</th>
				<th width="13%">
					下午<input class="th_check" type="checkbox" id="all_pm">
				</th>
				<th width="13%">
					夜班<input class="th_check" type="checkbox" id="all_night">
				</th>
				<th width="13%">
					早中晚班<input class="th_check" type="checkbox" id="all_day">
				</th>
				<th width="13%">额外分值(分)</th>
				<th width="13%">0点后(时)</th>
			</tr>
		</table>
    <div class="approval">
      <div class="approval-level clearfix">
        <div class="approval-title">
          <span class="Validform_checktip">*</span>一级审批人员:
        </div>
				<input type="button" id="approval-btn-1" class="approval-person" title="一级审批人员" />
				<img class="approval-btn" onclick="queryApproval('approval-btn-1')" src="../assets/add.png">
				<img class="approval-btn" style="margin-left:7px" name="btnDelapprover" onclick="delApproval('approval-btn-1');" src="../assets/delete.png">
      </div>
      <div class="approval-level clearfix">
        <div class="approval-title">
          二级审批人员:
        </div>
				<input type="button" id="approval-btn-2" class="approval-person" title="一级审批人员" />
				<img class="approval-btn" onclick="queryApproval('approval-btn-2')" src="../assets/add.png">
				<img class="approval-btn" style="margin-left:7px" name="btnDelapprover" onclick="delApproval('approval-btn-2');" src="../assets/delete.png">
      </div>
      <div class="approval-level clearfix">
        <div class="approval-title">
          三级审批人员:
        </div>
				<input type="button" id="approval-btn-3" class="approval-person" title="一级审批人员" />
				<img class="approval-btn" onclick="queryApproval('approval-btn-3')" src="../assets/add.png">
				<img class="approval-btn" style="margin-left:7px" name="btnDelapprover" onclick="delApproval('approval-btn-3');" src="../assets/delete.png">
      </div>
      <div class="approval-level clearfix">
        <div class="approval-title">
          四级审批人员:
        </div>
				<input type="button" id="approval-btn-4" class="approval-person" title="一级审批人员" />
				<img class="approval-btn" onclick="queryApproval('approval-btn-4')" src="../assets/add.png">
				<img class="approval-btn" style="margin-left:7px" name="btnDelapprover" onclick="delApproval('approval-btn-4');" src="../assets/delete.png">
      </div>
      <div class="approval-level clearfix">
        <div class="approval-title">
          五级审批人员:
        </div>
				<input type="button" id="approval-btn-5" class="approval-person" title="一级审批人员" />
				<img class="approval-btn" onclick="queryApproval('approval-btn-5')" src="../assets/add.png">
				<img class="approval-btn" style="margin-left:7px" name="btnDelapprover" onclick="delApproval('approval-btn-5');" src="../assets/delete.png">
      </div>
    </div>
    <div class="actions">
      <button class="btn" style="font-weight: 400;" type="button" id="cancel" onclick="back()">取消</button>
      <button class="btn" style="font-weight: 400;" type="button" id="cancel" onclick="save()">保存</button>
      <button class="btn" style="font-weight: 400;" type="button" id="cancel" onclick="submit()">提交审批</button>
    </div>
    <div class="batch-add-pane" id="batch_add_pane">
      <p>确定要批量录入吗？</p>
      <button type="button" id="batch_add_cancel" onclick="cancelModel('batch_add_pane')">
        取消
      </button>
      <button type="button" id="batch-add-confirm" onclick="batchAddConfirm()">确定</button>
    </div>
	</div>

		<!-- 部门选择弹出框 -->
		<script id="recharge-tpl" type="text/template">
			<div id="role" style="width: 250px; float: left; ; height: 300px;background: #eeeeee">
				<div class="title">部门列表</div>
				<div id="treeParentArea" valign=top style="width: 100%;height: 500px;">
					<ul id="tree" class="ztree" style="overflow:auto;margin:0px;height:698px"></ul>
				</div>
			</div>
		</script>

		<script type="text/javascript">
			$(function(){
				getCurrentDept();
			});

			function ShowAction() {
				var param = {'0':'模版描述'};
				var tit = "部门选择";
				jsdialog(tit, RpTpl($("#recharge-tpl").html(), param), "", "None", function (data) {  alert(data);},
					function (data) {
						//alert('ok---'+right_click_node.id);
						//alert(data);
						$("#txtdept").val(right_click_node.name);
						$("#dept_id").val(right_click_node.id);
						$("#deptName").text(right_click_node.name);

						queryUsers();
					},
					function () {
						createTree();
					});
			}
			function RpTpl(tpl, obj) {
				var re = tpl;
				if (!tpl || tpl.length <= 0) return re;
				if (!obj || typeof obj != "object") return re;
				for (k in obj) {
					re = re.replace("{#" + k + "#}", obj[k]);
				}
				return re;
			}

		</script>

		<script type="text/javascript"
				src="/xyzg/system/common/scripts/utils.js"></script>
		<script type="text/javascript"
				src="/xyzg/system/common/scripts/zDialog.js"></script>
		<%--<script type="text/javascript" src="/xyzg/scripts/lhgdialog/lhgdialog.js?skin=idialog"></script>--%>
		<script type="text/javascript" src="/xyzg/scripts/zTree/js/jquery.ztree.all-3.5.min.js"></script>
		<script src="/xyzg/workatten/attendance/deptTreeJs.js"></script>
		<link rel="stylesheet" href="/xyzg/scripts/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css">

</body>
</html>
